import { defineStore } from 'pinia';
import { jwtDecode } from 'jwt-decode'; // 使用 jwt-decode 库

export const useAuthStore = defineStore('auth', {
    state: () => ({
        jwtToken: '' as string,
        decodedToken: {} as Chat.JwtPayload,
    }),
    actions: {
        // 解析 Token 并更新状态
        parseToken(token: string) {
            try {
                this.jwtToken = token;
                this.decodedToken = jwtDecode<Chat.JwtPayload>(token);
            } catch (error) {
                console.error('JWT 解析失败:', error);
                this.jwtToken = '';
                this.decodedToken = {sub:""};
            }
        },
        // 清除 Token
        clearToken() {
            this.jwtToken = '';
            this.decodedToken = {sub:""};
        },
    },
    getters: {
        //获取用户信息
        getUser:(state) => state.decodedToken,
        // 检查是否已登录（示例）
        isLoggedIn: (state) => !!state.jwtToken,
        // 获取用户权限（示例）
        userPermissions: (state) => state.decodedToken?.pri || [],
    },
});